--
-- Constrains y otros detalles sobre la tabla pre
--

ALTER TABLE public.pre
DROP CONSTRAINT IF EXISTS pre_cod;

ALTER TABLE public.pre
ADD CONSTRAINT pre_cod UNIQUE (COD);


CREATE FUNCTION public.tg_pre_upd_del()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
  IF ((TG_OP = 'UPDATE') AND (OLD.COD <> NEW.COD)) THEN
    UPDATE COMM SET CODPRE = NEW.COD WHERE COMM.CODPRE = OLD.COD;
	RETURN NEW;
  END IF;
  IF (TG_OP = 'DELETE') AND 
     EXISTS (SELECT * FROM COMM WHERE CODPRE = OLD.COD) THEN
     RAISE EXCEPTION 'Hay comprobantes ya generados con este precio, no puede eliminarse';
  END IF;
END;
$BODY$;

ALTER FUNCTION public.tg_pre_upd_del()
    OWNER TO abacouser;


CREATE TRIGGER pre_upd_del
    BEFORE UPDATE OR DELETE
    ON public.pre
    FOR EACH ROW
    EXECUTE PROCEDURE public.tg_pre_upd_del();

--
SELECT aaversion('498.02','498.01');
--

